package com.wsc.wisdomchinaqinghe.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.ACache;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.JieDaoTeSheActivity;
import com.wsc.wisdomchinaqinghe.activitity.JuWeiXinXiActivity;
import com.wsc.wisdomchinaqinghe.activitity.LifeServerActivity;
import com.wsc.wisdomchinaqinghe.activitity.LivingExpensesActivity;
import com.wsc.wisdomchinaqinghe.activitity.PageInfoDetailActivity;
import com.wsc.wisdomchinaqinghe.activitity.PeripheralSearchActivity;
import com.wsc.wisdomchinaqinghe.activitity.ReceptionCenterActivity;
import com.wsc.wisdomchinaqinghe.activitity.ShangjiaCuXiaoActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.CareTeenagersActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.CompanyInfoActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.FloorEventActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.FloorInfoActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.HelpOldManActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.PeopleControlActivity;
import com.wsc.wisdomchinaqinghe.activitity.wisdomParty.PartyActivity;
import com.wsc.wisdomchinaqinghe.activitity.wisdomParty.PartyLoginActivity;
import com.wsc.wisdomchinaqinghe.adapter.SiDaGongNengAdapter;
import com.wsc.wisdomchinaqinghe.application.MyApplication;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.HomeModule;
import com.wsc.wisdomchinaqinghe.javaBean.HomeModuleBean;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.javaBean.StreetInfoListBean;
import com.wsc.wisdomchinaqinghe.javaBean.wisdomParty.PartyUserBean;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyGridView;
import com.wsc.wisdomchinaqinghe.view.MyToast;

import java.util.List;

public class BanKuaiFragment extends Fragment implements View.OnClickListener,ContributorView{
    private boolean ishide = false;
    private ContributorPresenter contributorPresenter;
    private Context context;
    private PullToRefreshListView lv_today_information;
    private ListView actualListView;
    private String cidNumber;
    private MyApplication myApplication;
    private final String HOMEMODULELISTFLAG="HOMEMODULELISTFLAG";
    private final String LOCATION_FLAG="LOCATION_FLAG";
    private ACache aCache;
    private String aCacheFlagKey=BanKuaiFragment.class.getSimpleName();
    private ListStockAdapter listStockAdapter;
    private MyToast myToast;
    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_bankuai,container,false);
        context=getActivity();
        myToast =new MyToast(context);
        aCache=ACache.get(context);
        myApplication = (MyApplication) getActivity().getApplication();
        contributorPresenter = new ContributorPresenter(this, context);
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", context);
        if (locationString.length() > 0) {
            StreetInfoListBean streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber=streetInfoListBean.getId();
        }
        initview(view);
        return view;
    }

    private void initview(View view) {
        lv_today_information = (PullToRefreshListView) view.findViewById(R.id.lv_today_information);
        lv_today_information.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        actualListView = lv_today_information.getRefreshableView();

        actualListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        Tools.showRefreshView(lv_today_information);

        lv_today_information.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                // Update the LastUpdatedLabe
                // 处理下拉刷新的业务
                if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                    if(cidNumber!=null)
                    {
                        //获取新闻消息
                        contributorPresenter.getHomeModule(cidNumber,1,HOMEMODULELISTFLAG);
                    }else
                    {
                        //先获取词典Number 再获取新闻消息
                        String city= myApplication.getLocationCity();
                        String country=myApplication.getLocationDistrict();
                        contributorPresenter.getHomeFetchStreet(city,country,LOCATION_FLAG);
                    }
                }

            }
        });
    }


    private void getData()
    {
        if(listStockAdapter==null)
        {
            if(aCache.getAsString(aCacheFlagKey)!=null)
            {
                List<HomeModuleBean> homeModuleBeanList=JsonTools.jsonStringToList(aCache.getAsString(aCacheFlagKey),HomeModuleBean.class);
                if(homeModuleBeanList!=null && homeModuleBeanList.size()>0)
                {
                    listStockAdapter = new ListStockAdapter(homeModuleBeanList);
                    actualListView.setAdapter(listStockAdapter);
                }
            }else {
                if(cidNumber!=null)
                {
                    //获取新闻消息
                    contributorPresenter.getHomeModule(cidNumber,1,HOMEMODULELISTFLAG);
                }else
                {
                    //先获取词典Number 再获取新闻消息
                    String city= myApplication.getLocationCity();
                    String country=myApplication.getLocationDistrict();
                    contributorPresenter.getHomeFetchStreet(city,country,LOCATION_FLAG);
                }
            }
        }

    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
//        Log.e("http",flag+":"+jsonString);
        try {
            //banner
            if (flag.equals(HOMEMODULELISTFLAG)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    List<HomeModuleBean> homeModuleBeanList=JsonTools.jsonStringToList(jsonMessage,HomeModuleBean.class);
                    if(homeModuleBeanList!=null && homeModuleBeanList.size()>0)
                    {
                        aCache.put(aCacheFlagKey,jsonMessage,8*60);
                        listStockAdapter = new ListStockAdapter(homeModuleBeanList);
                        actualListView.setAdapter(listStockAdapter);
                    }
                }

            }else if(flag.equals(LOCATION_FLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code=respObj.getCode();
                if(code.equals("200"))
                {
                    String message=JsonTools.objectToJsonString(respObj.getMessage());
                    List<StreetInfoListBean> listData=JsonTools.jsonStringToList(message,StreetInfoListBean.class);
                    if(listData!=null &&listData.size()>0)
                    {
                        Tools.setSharedPreferencesStrings(Constant.SharePreferenceLocation,JsonTools.objectToJsonString(listData.get(0)),context);
                        cidNumber=listData.get(0).getId();
                        //获取新闻消息
                        contributorPresenter.getHomeModule(cidNumber,1,HOMEMODULELISTFLAG);
                    }
                }
            }

        } catch (Exception e) {

        }
    }

    /**
     *
     * @Description 股票适配器
     * @author jaily.zhang
     * @date 2014-9-9 下午3:39:03
     * @version V1.3.1
     */
    class ListStockAdapter extends BaseAdapter {
        List<HomeModuleBean> homeModuleBeanList;

        public ListStockAdapter(List<HomeModuleBean> listPlansBeans) {
            this.homeModuleBeanList = listPlansBeans;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return homeModuleBeanList.size();
        }


        @Override
        public Object getItem(int position) {
             // TODO Auto-generated method stub
            return homeModuleBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
           // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            try {
                NestedListview v = null;
                if (convertView == null) {
                    v = new NestedListview(context, homeModuleBeanList.get(position));
                    convertView = v.getView();
                    convertView.setTag(v.getView());
                } else {
                    v = new NestedListview(context, homeModuleBeanList.get(position));
                    convertView = v.getView();
                }
            } catch (Exception e) {
                // TODO: handle exception
            }
            return convertView;
        }

    }

    /**
     *
     * @Description 嵌套listView
     * @author jaily.zhang
     * @date 2015-1-9 下午12:57:17
     * @version V1.3.1
     */
    class NestedListview {

        private View myview;
        private HomeModuleBean homeModuleBean;
        private Context mycontext;
        private MyGridView myGridView;
        private TextView tv_title;
        private SiDaGongNengAdapter adapter;
        private List<HomeModule> homeModuleList;

        public NestedListview(Context context, HomeModuleBean listData) {
            this.mycontext = context;
            this.homeModuleBean = listData;
            if (listData.getChild() != null) {
                String jsonString=JsonTools.objectToJsonString(listData.getChild());
                if(jsonString!=null)
                {
                    homeModuleList=JsonTools.jsonStringToList(jsonString,HomeModule.class);
                    if(homeModuleList!=null && homeModuleList.size()>0)
                    {
                        this.adapter = new SiDaGongNengAdapter(context, homeModuleList,true);
                    }
                }

            }
            InitView();
        }

        private void InitView() {
            // TODO Auto-generated method stub
            try {
                myview = LayoutInflater.from(mycontext).inflate(R.layout.bankuailayout, null);
                myGridView = (MyGridView) myview.findViewById(R.id.mygridview);
                myGridView.setHaveScrollbar(false);
                tv_title=(TextView) myview.findViewById(R.id.tv_title);
                tv_title.setText(homeModuleBean.getName());
                myGridView.setAdapter(adapter);
                myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        HomeModule homeModule=homeModuleList.get(position);
                        String nameModule=homeModule.getName();
                        String idModule=homeModule.getMid();
                        if(idModule.equals(Constant.SheQuJianJie))
                        {
                            //社区简介
                            Intent intent=new Intent(context, PageInfoDetailActivity.class);
                            intent.putExtra("id",idModule);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }else if (idModule.equals(Constant.BanGongZhiNeng))
                        {
                            //办公职能
                            Intent intent=new Intent(context, PageInfoDetailActivity.class);
                            intent.putExtra("id",idModule);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.SheQuXinXi))
                        {
                            //社区信息
                            Intent intent=new Intent(context, JuWeiXinXiActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.WangGeGuanLi))
                        {
                            //网格管理
                            Intent intent=new Intent(context, PageInfoDetailActivity.class);
                            intent.putExtra("id",idModule);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.SheQuTeShe))
                        {
                            //社区特色
                            Intent intent=new Intent(context, JieDaoTeSheActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("idmodule",idModule);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ZhouBianKuaiCha))
                        {
                            //周边快查
                            Intent intent=new Intent(context, PeripheralSearchActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.GuanXinQingShaoNian))
                        {
                            //关心青少年
                            Intent intent=new Intent(context, CareTeenagersActivity.class);
                            intent.putExtra("cid",cidNumber);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ShengHuoJiaoFei))
                        {
                            //生活缴费
//                            myToast.showShort("该功能正在升级中，请稍后...");
                            Intent intent=new Intent(context, LivingExpensesActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ShengHuoFuWu))
                        {
                            //生活服务
                            Intent intent=new Intent(context, LifeServerActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ShangJiaCuXiao))
                        {
                            //商家促销
                            Intent intent=new Intent(context, ShangjiaCuXiaoActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.LouYuXinXi))
                        {
                            //楼宇信息
                            Intent intent = new Intent(context, FloorInfoActivity.class);
                            intent.putExtra("name","楼宇搜索");
                            intent.putExtra("id",cidNumber);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.QiYeXinXi))
                        {
                            //企业信息
                            Intent intent = new Intent(context, CompanyInfoActivity.class);
                            intent.putExtra("name","企业搜索");
                            intent.putExtra("id",cidNumber);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.LouYuHuoDong))
                        {
                            //楼宇活动
                            Intent intent = new Intent(context, FloorEventActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            intent.putExtra("type",1);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.SheQuHuoDong))
                        {
                            //社区活动
                            Intent intent = new Intent(context, FloorEventActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            intent.putExtra("type",0);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ShouLiCenter))
                        {
                            //受理中心
                            Intent intent=new Intent(context, ReceptionCenterActivity.class);
                            intent.putExtra("id",cidNumber);
                            intent.putExtra("name",nameModule);
                            startActivity(intent);
                        }
//                        else if(nameModule.equals("党员组织管理"))
//                        {
//
//                        }
                        else if(idModule.equals(Constant.ZhuLaoService))
                        {
                            //助老服务
                            Intent intent = new Intent(context, HelpOldManActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            intent.putExtra("idmodule",idModule);
                            startActivity(intent);
                        }
                        else if(idModule.equals(Constant.ZhuCanService))
                        {
                            //助残服务
                            Intent intent = new Intent(context, HelpOldManActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            intent.putExtra("idmodule",idModule);
                            startActivity(intent);
                        }else if(idModule.equals(Constant.BaiXingJianDu))
                        {
                            // 百姓监督
                            Intent intent = new Intent(context, PeopleControlActivity.class);
                            intent.putExtra("name",nameModule);
                            intent.putExtra("cid",cidNumber);
                            startActivity(intent);
                        }
                        else if(nameModule.equals("智慧党建"))
                        {
                            String jsonMessage=Tools.getSharedPreferencesStrings(Constant.SharePreferencePartyUserInfo,"",context);
                            if(jsonMessage.equals(""))
                            {
                                // 智慧党建
                                Intent intent=new Intent(context, PartyLoginActivity.class);
                                intent.putExtra("name",nameModule);
                                intent.putExtra("cid",cidNumber);
                                startActivity(intent);
                            }else {
                                PartyUserBean partyUserBean=JsonTools.jsonStringToObject(jsonMessage,PartyUserBean.class);
                                Intent intent=new Intent(context,PartyActivity.class);
                                intent.putExtra("pId",partyUserBean.getId());
                                intent.putExtra("cId",cidNumber);
                                startActivity(intent);
                            }
                        }

                    }
                });

            } catch (Exception e) {
                // TODO: handle exception
            }
        }

        public View getView() {
            // TODO Auto-generated method stub
            return myview;
        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        lv_today_information.onRefreshComplete();
    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ishide = hidden;
        if(hidden)
        {
        }else
        {
            getData();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (ishide) {

        } else {
            getData();
        }

        MobclickAgent.onPageStart(BanKuaiFragment.class.getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(BanKuaiFragment.class.getSimpleName());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
        }
    }
}
